package com.haiheng.adscreen

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.haiheng.common.constant.AppConstant
import com.haiheng.commonlibrary.MainActivity
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.utils.ApplicationUtils

/**
 *
 * @Des:防止第三方输入法退出
 * @Author: hwz
 * @Date:2023/3/17 0017
 * @Version: 1.0
 */
class AppForegroundListener : Application.ActivityLifecycleCallbacks {
    public var appInForeground = false
    private val handler = Handler(Looper.getMainLooper())


    override fun onActivityResumed(activity: Activity) {
//        LogUtils.e("onActivityResumed packageName :${activity.packageName} componentName:${activity.componentName}")
        appInForeground = true

    }

    override fun onActivityPaused(activity: Activity) {
        LogUtils.e("AppForegroundListener packageName :${activity.packageName} componentName:${activity.componentName}")
        // 应用切换到后台的逻辑处理 ,是否退出后重新启动
        if (AppConstant.isExitOpenApp()){
            appInForeground = false
            handler.postDelayed({
                LogUtils.e("延迟1s后的状态：$appInForeground  isExt: ${AppConstant.isExitOpenApp()}")
                if (!appInForeground){
                    val intent = Intent(ApplicationUtils.application, MainActivity::class.java)
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    ApplicationUtils.application.startActivity(intent)
                }
            },1200)
        }
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        appInForeground = true
        LogUtils.e("onActivityCreated packageName :${activity.packageName} componentName:${activity.componentName}")

    }

    override fun onActivityStarted(activity: Activity) {}

    override fun onActivityStopped(activity: Activity) {}

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

    override fun onActivityDestroyed(activity: Activity) {}
}
